import React from 'react';
import dialog from 'Utils/dialog';
import LittleButton from 'Component/Page/CommonComponents/LittleButton';
import * as routerActions from 'react-router-redux';
import { List, InputItem, TextareaItem, WhiteSpace, Popup, Checkbox } from 'antd-mobile';
import Api from 'Utils/api';
import { generateUUID } from 'Utils/index';
import { connect } from 'react-redux';
import { CaptchaSeconds, API_HOST } from 'Constants/config';
import DefaultFirstPicker from 'Component/DefaultFirstPicker';
import UploadVideo from 'Component/Page/CommonComponents/UploadVideo';
import BottomButton from '../../BottomButton';
import Recording from './../CommonComponents/Record/Recording'
import './index.scss';

const CheckboxItem = Checkbox.CheckboxItem;

class InformPage extends React.PureComponent {
  constructor(props) {
    super(props);
    const formValue = sessionStorage.getItem('formValue') ? JSON.parse(sessionStorage.getItem('formValue')) : {};
    this.state = {
      remainingSecond: CaptchaSeconds,
      title: formValue.title ? formValue.title : '',
      content: formValue.content ? formValue.content : '',
      name: formValue.name ? formValue.name : '',
      idCard: formValue.idCard ? formValue.idCard : '',
      phone: formValue.phone ? formValue.phone : '',
      code: formValue.code ? formValue.code : '',
      media: formValue.media ? formValue.media : '',
      businessInfo: {
        id: props.businessInfo.id,
        name: props.businessInfo.name,
        type: props.businessInfo.type,
      },
      anonymous: false
    };
    this.canSendCaptcha = true;
    this.sendCaptcha = ::this.sendCaptcha;
    this.countDownSeconds = ::this.countDownSeconds;
    this.changeTitle = ::this.changeTitle;
    this.changeComplaints = ::this.changeComplaints;
    this.changeContent = ::this.changeContent;
    this.changeName = ::this.changeName;
    this.changeIdCard = ::this.changeIdCard;
    this.changePhone = ::this.changePhone;
    this.changeCode = ::this.changeCode;
    this.wxConfig = ::this.wxConfig;
    this.showModal = ::this.showModal;
    this.getVoiceLocalId = ::this.getVoiceLocalId;
    this.changeMessage = ::this.changeMessage;
    this.upReports = ::this.upReports;
    this.weixiJsdk = ::this.weixiJsdk;
  }
  componentDidMount() {
    this.weixiJsdk();
  }
  componentWillUnmount() {
    clearInterval(this.timer);
    this.canSendCaptcha = true;
  }
  getVoiceLocalId(val) {
    console.log('音频数据ID', val);
    this.setState({
      media: val,
    })
  }
  weixiJsdk() {
    const config = new Api({
      method: 'GET',
      path: '/wechat/config/jsapi',
      query: {
        url: encodeURIComponent(location.href.split('#')[0]),
      },
      success: (json) => {
        this.wxConfig(json);
      },
    });
    config.run();
  }
  wxConfig(json) {
    wx.config({
      debug: false,
      appId: json.app_id,
      timestamp: json.timestamp,
      nonceStr: json.nonce_str,
      signature: json.signature,
      jsApiList: [
        'uploadVoice',
        'startRecord',
        'stopRecord',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'onVoicePlayEnd',
        'uploadVoice',
      ],
    });
  }

  changeTitle(val) {
    this.setState({
      title: val,
    });
  }
  changeComplaints(val) {
    this.setState({
      complaints: val,
    });
  }
  changeContent(val) {
    this.setState({
      content: val,
    });
  }
  changeName(val) {
    this.setState({
      name: val,
    });
  }
  changeIdCard(val) {
    this.setState({
      idCard: val,
    });
  }
  changePhone(val) {
    this.setState({
      phone: val,
    });
  }
  changeCode(val) {
    this.setState({
      code: val,
    });
  }
  changeAnonymous(e) {
    this.setState({
      anonymous: e.target.checked
    });
  }
  showModal() {
    const { voiceState } = this.state;
    Popup.show(
      <Recording
        voiceState={voiceState}
        getVoiceLocalId={this.getVoiceLocalId}
      />
      , { animationType: 'slide-up' }
    );
  }
  changeMessage(val) {
    this.setState({
      messageWay: val[0],
    });
  }
  /**
   * 验证码倒计时
   */
  countDownSeconds() {
    const remainingSecond = this.state.remainingSecond - 1;
    if (remainingSecond < 0) {
      this.canSendCaptcha = true;
      clearInterval(this.timer);
      this.timer = undefined;
    } else {
      if (!this.timer) {
        this.timer = setInterval(this.countDownSeconds, 1000);
      }
      this.setState(preState => (Object.assign({}, preState, {
        remainingSecond,
      })));
    }
  }
  /**
   * 发送验证码
   */
  sendCaptcha() {
    const { phone } = this.state;
    if (!this.canSendCaptcha) {
      return;
    }
    this.canSendCaptcha = false;
    setTimeout(() => {
      this.setState({
        remainingSecond: CaptchaSeconds,
      }, () => {
        this.countDownSeconds();
      });
    }, 0);
    const self = this;
    const api = new Api({
      method: 'POST',
      path: '/phone/verify_code',
      data: {
        phone,
      },
      error: () => {
        self.setState({
          remainingSecond: 0,
        }, () => {
          self.canSendCaptcha = true;
          clearInterval(this.timer);
          this.timer = undefined;
        });
      },
    });
    api.run();
  }
  handleUpload(newId) {
    this.setState({
      media: newId,
    })
  }
  isok() {
    const {
      title,
      businessInfo,
      name,
      idCard,
      phone,
      code,
      content
    } = this.state;
    return (
      businessInfo.id > 0
      && name
      && idCard
      && phone
      && code
      && title
      && content);
  }
  clear() {
    this.setState({
      src: '',
      remainingSecond: 0,
      title: '',
      content: '',
      name: '',
      idCard: '',
      phone: '',
      code: '',
      media: '',
      messageWay: '',
      businessInfo: {
        id: '',
        name: '',
        type: '',
      },
    }, () => { this.upload.clearSrc() });
    sessionStorage.removeItem('formValue');
  }
  upReports() {
    const {
      title, businessInfo, name, idCard, phone, code, content, media, messageWay, anonymous
    } = this.state;
    const self = this;
    const api = new Api({
      method: 'POST',
      path: '/reports/user',
      data: {
        title,
        report_target: businessInfo.name,
        enterprise_id: businessInfo.id,
        type: businessInfo.type,
        content,
        reporter: name,
        id_no: idCard,
        phone,
        code,
        video_audio: media,
        report_type: messageWay,
        uuid: generateUUID(),
        is_anonymity: anonymous
      },
      success: () => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => { self.props.dispatch(routerActions.goBack()); },
          },
        ];
        dialog.open('提示', '提交举报成功', buttons, 'center');
        this.clear();
      },
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  render() {
    const { title, businessInfo, name, idCard, phone, code, messageWay, content, remainingSecond,
      anonymous,
      messageDate = [
        {
          label: '视频',
          value: 'video',
        },
        {
          label: '音频',
          value: 'audio',
        },
      ], } = this.state;
    return (
      <div className="big-body">
        <div className="Inform">
          <div className="Inform-title">
            <span>我要举报</span>
          </div>
          <List className="my-list">
            <InputItem
              placeholder="请输入标题"
              type="string"
              value={title}
              onChange={this.changeTitle}
            >
              标题
            </InputItem>
            <InputItem
              className="reported"
              placeholder="请选择投诉对象"
              type="string"
              disabled
              value={businessInfo.name}
              onChange={this.changeMerchant}
            >
              投诉对象
              <LittleButton
                title="选择"
                width={128}
                height={50}
                onClick={() => {
                  const formValue = {
                    title,
                    businessInfo,
                    name,
                    idCard,
                    phone,
                    code,
                    content,
                  };
                  sessionStorage.setItem('formValue', JSON.stringify(formValue));
                  this.props.dispatch(routerActions.push('/select_business'));
                }}
                className="little-button big-font double-input"
              />
            </InputItem>
          </List>
          <WhiteSpace />
          <div className="content">
            <div className="content-title">内容</div>
            <TextareaItem
              rows={5}
              count={140}
              value={content}
              onChange={this.changeContent}
              placeholder="请输入内容"
            />
          </div>
          <List className="my-list">
            <InputItem
              placeholder="请输入举报人姓名"
              type="string"
              value={name}
              onChange={this.changeName}
            >
              举报人
              <CheckboxItem className="anonymous-check" checked={anonymous} onChange={this.changeAnonymous.bind(this)}>
                匿名
              </CheckboxItem>
            </InputItem>
            <InputItem
              placeholder="请输入身份证号"
              type="string"
              value={idCard}
              onChange={this.changeIdCard}
            >
              身份证号码
            </InputItem>
            <InputItem
              placeholder="请输入联系电话"
              onChange={this.changePhone.bind(this)}
              value={phone}
            >
              联系电话
              <LittleButton
                title={remainingSecond === 60 || remainingSecond === 0
                  ? '获取验证码'
                  : <span>剩余{remainingSecond}s</span>
                }
                width={200}
                height={60}
                className="little-button big-font in-input"
                onClick={this.sendCaptcha}
                disabled={!phone}
              />
            </InputItem>
            <InputItem
              placeholder="请输入验证码"
              type="string"
              value={code}
              onChange={this.changeCode}
            >
              验证码
            </InputItem>
          </List>
          <WhiteSpace />
          <div className="word-mode">
            <List>
              <DefaultFirstPicker
                value={[messageWay]}
                data={messageDate}
                extra="--请选择--"
                colnum={1}
                onChange={this.changeMessage}
                text="留言方式"
              />
            </List>
            <div className={`voice-img ${messageWay === 'audio' ? 'message-show' : 'message-hidden'}`}>
              <img onClick={this.showModal} src="./images/icons/icon_voice.png" alt="录音" />
              {this.state.media &&
              <p className="voice-ui">
                <audio src={`${API_HOST}/files/${this.state.media}`} controls="controls" className="audio-content">
                </audio>
              </p>
              }
            </div>
            <div className={`voice-img ${messageWay === 'video' ? 'message-show' : 'message-hidden'}`}>
              <UploadVideo
                ref={(ref) => { this.upload = ref; }}
                uploadHandle={this.handleUpload.bind(this)}
              />
            </div>
          </div>
        </div>
        <BottomButton
          okText="提交"
          okHandle={this.upReports}
          disabled={!this.isok()}
        />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    businessInfo: state.businessReducer,
  };
}

export default connect(mapStateToProps)(InformPage);
